<template>
  <view class="container">
    <view class="progress-bar">
      <view class="progress-inner" :style="{width: progress + '%'}"></view>
    </view>
    <view class="progress-text">{{currentIndex + 1}}/{{questions.length}}</view>
    
    <view class="question-card">
      <text class="question-text">{{currentQuestion.question}}</text>
      
      <view class="options">
        <view 
          v-for="(option, index) in currentQuestion.options" 
          :key="index"
          class="option-item"
          :class="{selected: selectedOption === index}"
          @click="selectOption(index)">
          <text class="option-text">{{option.text}}</text>
        </view>
      </view>
    </view>
    
    <view class="buttons">
      <button 
        class="nav-btn prev" 
        :disabled="currentIndex === 0" 
        @click="prevQuestion">上一题</button>
      <button 
        class="nav-btn next" 
        :disabled="selectedOption === null" 
        v-if="currentIndex === questions.length - 1"
        @click="finishTest">完成</button>
    </view>
  </view>
</template>

<script>
import questionData from '@/data/questions.js';

export default {
  data() {
    return {
      questions: questionData,
      currentIndex: 0,
      answers: [],
      selectedOption: null
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex];
    },
    progress() {
      return (this.currentIndex / this.questions.length) * 100;
    }
  },
  onLoad() {
    // 尝试从存储中获取已保存的答案
    try {
      const savedAnswers = uni.getStorageSync('mbtiAnswers');
      const savedIndex = uni.getStorageSync('mbtiCurrentIndex');
      
      if (savedAnswers && savedAnswers.length) {
        this.answers = savedAnswers;
        if (savedIndex !== '' && savedIndex < this.questions.length) {
          this.currentIndex = savedIndex;
        }
        this.selectedOption = this.getSelectedOptionForCurrentQuestion();
      } else {
        // 初始化答案数组
        this.answers = new Array(this.questions.length).fill(null);
      }
    } catch (e) {
      console.error('读取存储时发生错误:', e);
      // 如果读取失败，初始化答案数组
      this.answers = new Array(this.questions.length).fill(null);
    }
  },
  methods: {
    selectOption(index) {
      this.selectedOption = index;
      this.answers[this.currentIndex] = {
        questionId: this.currentQuestion.id,
        selectedOption: index,
        dimension: this.currentQuestion.dimension,
        value: this.currentQuestion.options[index].value
      };
      
      // 保存答案到存储
      this.saveAnswers();
      
      // 如果不是最后一题，自动前进到下一题
      if (this.currentIndex < this.questions.length - 1) {
        setTimeout(() => {
          this.nextQuestion();
        }, 500); // 延迟500毫秒，让用户看到选择效果
      }
    },
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
        this.selectedOption = this.getSelectedOptionForCurrentQuestion();
        // 保存当前索引到存储
        uni.setStorageSync('mbtiCurrentIndex', this.currentIndex);
      }
    },
    nextQuestion() {
      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex++;
        this.selectedOption = this.getSelectedOptionForCurrentQuestion();
        // 保存当前索引到存储
        uni.setStorageSync('mbtiCurrentIndex', this.currentIndex);
      }
    },
    getSelectedOptionForCurrentQuestion() {
      const answer = this.answers[this.currentIndex];
      return answer ? answer.selectedOption : null;
    },
    saveAnswers() {
      try {
        // 保存答案到持久化存储
        uni.setStorageSync('mbtiAnswers', this.answers);
        uni.setStorageSync('mbtiCurrentIndex', this.currentIndex);
      } catch (e) {
        console.error('保存答案时发生错误:', e);
      }
    },
    finishTest() {
      const result = this.calculateResult();
      uni.setStorageSync('mbtiResult', result);
      
      // 测试完成后清除答案缓存（可选，取决于是否希望用户能再次查看答案）
      // uni.removeStorageSync('mbtiAnswers');
      // uni.removeStorageSync('mbtiCurrentIndex');
      
      uni.navigateTo({
        url: '/pages/result/result'
      });
    },
    calculateResult() {
      // 初始化维度计数
      const dimensions = {
        E: 0, I: 0,
        S: 0, N: 0,
        T: 0, F: 0,
        J: 0, P: 0
      };
      
      // 计算每个维度的得分
      this.answers.forEach(answer => {
        if (answer && answer.dimension && answer.value) {
          dimensions[answer.value]++;
        }
      });
      
      // 确定每个维度的结果
      const result = {
        EI: dimensions.E > dimensions.I ? 'E' : 'I',
        SN: dimensions.S > dimensions.N ? 'S' : 'N',
        TF: dimensions.T > dimensions.F ? 'T' : 'F',
        JP: dimensions.J > dimensions.P ? 'J' : 'P'
      };
      
      // 计算每个维度的百分比
      const percentages = {
        EI: Math.round(Math.max(dimensions.E, dimensions.I) / (dimensions.E + dimensions.I) * 100),
        SN: Math.round(Math.max(dimensions.S, dimensions.N) / (dimensions.S + dimensions.N) * 100),
        TF: Math.round(Math.max(dimensions.T, dimensions.F) / (dimensions.T + dimensions.F) * 100),
        JP: Math.round(Math.max(dimensions.J, dimensions.P) / (dimensions.J + dimensions.P) * 100)
      };
      
      return {
        type: result.EI + result.SN + result.TF + result.JP,
        dimensions: result,
        percentages: percentages,
        raw: dimensions
      };
    }
  }
};
</script>

<style>
.container {
  padding: 30rpx;
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box; /* 确保内边距包含在高度中 */
  overflow: hidden; /* 防止出现滚动条 */
}
.progress-bar {
  width: 100%;
  height: 16rpx;
  background-color: #f0f0f0;
  border-radius: 8rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
}
.progress-inner {
  height: 100%;
  background-color: #4a6bff;
  transition: width 0.3s;
}
.progress-text {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  margin-bottom: 20rpx; /* 减少底部间距 */
}
.question-card {
  flex: 1;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
  padding: 30rpx; /* 减少内边距 */
  margin-bottom: 20rpx; /* 减少底部间距 */
  display: flex;
  flex-direction: column;
  overflow-y: auto; /* 如果问题内容过长，可滚动 */
  max-height: calc(100vh - 200rpx); /* 限制最大高度，留出按钮空间 */
}
.question-text {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 40rpx; /* 减少底部间距 */
  line-height: 1.5;
}
.options {
  display: flex;
  flex-direction: column;
}
.option-item {
  padding: 24rpx; /* 减少内边距 */
  border-radius: 12rpx;
  border: 1px solid #eee;
  margin-bottom: 20rpx; /* 减少选项间距 */
  transition: all 0.2s;
}
.option-item.selected {
  background-color: #f0f4ff;
  border-color: #4a6bff;
}
.option-text {
  font-size: 32rpx;
  color: #555;
  line-height: 1.4;
}
.buttons {
  display: flex;
  justify-content: space-between;
  padding-bottom: 30rpx; /* 确保按钮底部有适当间距 */
  position: relative; /* 确保按钮位置正确 */
  z-index: 10; /* 确保按钮显示在最上层 */
}
.nav-btn {
  width: 45%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
}
.prev {
  background-color: #f7f7f7;
  color: #666;
}
.next {
  background-color: #4a6bff;
  color: white;
}
.nav-btn[disabled] {
  opacity: 0.5;
}
</style>